import 'package:aio/aio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:app/generated/app_strings.dart';
import 'package:app/src/http/model/material_requisition_model.dart';
import 'package:app/src/ui/dialog/dailog.dart';
import 'package:app/src/ui/route/helper/route_helper.dart';
import 'package:app/src/ui/route/works/public/items/ui_base.dart';
import 'package:app/src/ui/route/works/public/items/ui_card.dart';

import '../../../../../http/bean/works_2023/purcontract_bean.dart';
import '../../../../../http/bean/works_2023/purorderInfo_bean.dart';
import '../../../../../http/bean/worksdo/material_requisition_bean.dart';
import '../../../../../http/bean/wroks/dispatchingaudit_bean.dart';
import '../../../../../http/bean/ywx_limit.dart';
import '../../../../../utils/a_combined_utils.dart';
import '../../../../app_ui.dart';

///采购合同审核：物料信息
class UiPurContractAuditForm2 {
  static Widget build(
      BuildContext context, PurContractBean? materialInfo, YwxItem item,
      {String? title}) {
    return StatefulBuilder(builder: (context, setState) {
      List<Widget> children = [];
      if (StringUtils.isEmpty(title)) {
        title = AppStrings.of(context).MaterialInfo; //物料信息
      }
      children.add(UiBase.title(context, title,
          bottom: AppEdgeInsets.margin_bottom)); //标题
      children.add(UiBase.item(context, AppStrings.of(context).PurBodyCode,
          materialInfo?.PurBodyCode, null,
          isGrey: false, isAllowEmpty: true, isStart: false)); //子合同编号
      children.add(UiBase.item(context, AppStrings.of(context).ContractOutCode,
          materialInfo?.OutCode, null,
          isGrey: false, isAllowEmpty: true, isStart: false)); //子合同外部编号
      children.add(UiBase.item(context, AppStrings.of(context).SignDateDate,
          materialInfo?.getSignDateTime2(), null,
          isGrey: false, isAllowEmpty: true, isStart: false)); //签订日期*
      // children.add(UiBase.item(context, AppStrings.of(context).DeliveryDateTime,
      //     materialInfo?.getDeliveryDateTime(), null,
      //     isGrey: false, isAllowEmpty: true, isStart: false)); //要货日期*
      ///查看附件
      children.add(
          UiBase.itemWithButon(context, AppStrings.of(context).ToView2, () {
        if (StringUtils.isEmpty(materialInfo?.getBodyFileInfo())) {
          AppDialog.showDialogWithInfo(context,
              content: AppStrings.of(context).AttachmentEmpty); //当前附件为空!
          return;
        }
        AppRouteHelper.goPurcontractAuditDetailsFujianRoute(
            context, item, materialInfo?.getBodyFileInfo());
      }, margin: EdgeInsets.only(top: 8, bottom: 8)));
      children.add(_table(context, materialInfo!, item));
      var column = UiBase.column(context, children);
      var card = UiCard.build(context, column);
      return card;
    });
  }

  ///fixme Table表格里的行TabRow;每一行的表格数量必须相等。不然报错。
  ///fixme table嵌套table实现单元格合并。

  //表格线条颜色
  static Color _BorderColor = Colors.black12;

  //表格线条宽度
  static double _width = 1;

  ///背景色表格标题
  static Color _backgroundColorWithTableTitle = Colors.black12;
  static Color _backgroundColorWithWhite = Colors.white;
  static Color _backgroundColorWithGrey = ColorUtils.parseColor("#F7F6F3");
  static StateSetter? _setState = null;

  static Widget _table(
      BuildContext context, PurContractBean materialInfo, YwxItem item) {
    if (materialInfo?.PurContractList == null ||
        materialInfo!.PurContractList!.length <= 0) {
      return LibUi.getEmptyView();
    }
    //fixme 表格
    return StatefulBuilder(builder: (context, setState) {
      _setState = setState;
      //可以水平滑动的表格
      var scrolltable = _scrolltable(context, materialInfo, item);
      //水平滑动效果
      var singleChildScrollView = SingleChildScrollView(
          child: scrolltable, scrollDirection: Axis.horizontal);
      return Center(
        child: Container(
          child: singleChildScrollView,
          //width: 2400,
        ),
      );
    });
  }

  ///水平滑动表格
  static Widget _scrolltable(
      BuildContext context, PurContractBean materialInfo, YwxItem item) {
    if (materialInfo.PurContractList == null ||
        materialInfo.PurContractList!.length <= 0) {
      return AppUi.getEmptyView();
    }
    List<PurContractListBean> allDatas = materialInfo.PurContractList!;
    List<List<PurContractListBean>?> listDatas =
        materialInfo.getPurContractLists();
    var firstData = allDatas[0];
    var children = <TableRow>[];
    var isMT01 = firstData.isMT01(); //判断是否为原片
    _index = 0; //fixme 总序号
    //第一行标题栏
    List<Widget> titleChildren = [];
    titleChildren.add(_titleSerial(context, firstData, isMT01)); //序号
    titleChildren.add(_text(AppStrings.of(context).PurOrderCode)); //采购单号
    titleChildren.add(_titleAll(context, firstData, isMT01)); //标题
    var tableRow = TableRow(
        decoration: BoxDecoration(color: _backgroundColorWithTableTitle),
        children: titleChildren);
    children.add(tableRow);
    //第二行，内容行。
    for (int i = 0; i < listDatas.length; i++) {
      var datas = listDatas[i];
      var data = datas![0];
      List<Widget> rowChildren = [];
      //序号
      rowChildren.add(_contentSerial(context, datas));
      //PurOrderCode 采购单号
      var PurOrderCode = _text("${data.PurOrderCode}");
      rowChildren.add(PurOrderCode);
      rowChildren.add(_contentAll(context, datas, firstData, isMT01));
      var tableRow = TableRow(
        // decoration: BoxDecoration(color: _getColor(_index + 1)),
        decoration: BoxDecoration(color: _getColor(i)),
        children: rowChildren,
      );
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.all(
          color: _BorderColor, width: _width, style: BorderStyle.solid),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
      columnWidths: {
        0: FixedColumnWidth(80),
        1: FixedColumnWidth(200),
        2: FixedColumnWidth(2200),
      },
      children: children,
    );
    return table;
  }

  static FixedColumnWidth _FixedColumnWidth({double width = 100}) {
    return FixedColumnWidth(width);
  }

  static Map<int, TableColumnWidth>? _columnWidths() {
    return {
      0: FixedColumnWidth(200),
      1: _FixedColumnWidth(),
      2: _FixedColumnWidth(width: 200),
      3: _FixedColumnWidth(),
      4: _FixedColumnWidth(),
      5: _FixedColumnWidth(),
      6: _FixedColumnWidth(),
      7: _FixedColumnWidth(),
      8: _FixedColumnWidth(),
      9: _FixedColumnWidth(),
      10: _FixedColumnWidth(),
      11: _FixedColumnWidth(),
      12: _FixedColumnWidth(),
      13: _FixedColumnWidth(),
      14: _FixedColumnWidth(),
      15: _FixedColumnWidth(),
      16: _FixedColumnWidth(),
      17: _FixedColumnWidth(),
      18: _FixedColumnWidth(),
      19: _FixedColumnWidth(),
      20: _FixedColumnWidth(),
      21: _FixedColumnWidth(),
      22: _FixedColumnWidth(),
      23: _FixedColumnWidth(),
      24: _FixedColumnWidth(),
    };
  }

  ///内部嵌套表格(序号)
  static Widget _titleSerial(
      BuildContext context, PurContractListBean firstData, bool isMT01) {
    List<Widget> titleChildren = [];
    titleChildren.add(_text(AppStrings.of(context).TheSerial)); //序号
    var table = Table(
      border: TableBorder.symmetric(
        inside: BorderSide(
            color: _BorderColor, width: _width, style: BorderStyle.solid),
      ),
      children: [
        TableRow(children: titleChildren),
      ],
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///内部嵌套表格(标题)
  static Widget _titleAll(
      BuildContext context, PurContractListBean firstData, bool isMT01) {
    List<Widget> titleChildren = [];
    titleChildren.add(_text(AppStrings.of(context).PurchaseOrderNumber)); //请购单号
    titleChildren.add(_text(AppStrings.of(context).TypeOfMaterial)); //物料类型
    titleChildren.add(_text(AppStrings.of(context).MaterialName3)); //物料名称
    titleChildren.add(_text(AppStrings.of(context).MaterialCode)); //物料编码
    if (isMT01) {
      titleChildren.add(_text(AppStrings.of(context).ItemWidth)); //宽
      titleChildren.add(_text(AppStrings.of(context).ItemHeight)); //高
    }
    titleChildren.add(_text(AppStrings.of(context).Width_Height)); //规格型号
    if (!isMT01) {
      titleChildren
          .add(_text(AppStrings.of(context).PDMinNum, isStart: false)); //请购数量
    }
    titleChildren.add(_text(AppStrings.of(context).Unit, isStart: false)); //单位
    titleChildren.add(_text(AppStrings.of(context).QuantityPurchased2,
        isStart: false)); //采购数量
    if (isMT01) {
      titleChildren.add(_text(AppStrings.of(context).Area)); //面积
      titleChildren.add(_text(AppStrings.of(context).areaprice2)); //面积单价
      titleChildren.add(_text(AppStrings.of(context).tons)); //顿重
      titleChildren.add(_text(AppStrings.of(context).tonsprice)); //顿重单价
    } else {
      titleChildren
          .add(_text(AppStrings.of(context).Price2, isStart: false)); //单价
    }
    titleChildren.add(_text(AppStrings.of(context).DAmount)); //金额
    if (isMT01) {
      titleChildren.add(_text(AppStrings.of(context).QualityGrade2)); //质量等级
    }
    titleChildren.add(_text(AppStrings.of(context).ManufacturerName)); //品牌
    titleChildren.add(_text(AppStrings.of(context).Note)); //备注
    var table = Table(
      border: TableBorder.symmetric(
        inside: BorderSide(
            color: _BorderColor, width: _width, style: BorderStyle.solid),
      ),
      children: [
        TableRow(children: titleChildren),
      ],
      columnWidths: _columnWidths(),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///下标；这里主要作为总序号使用。
  static int _index = 0; //fixme 使用的使用，第一次记得设置为0；

  ///内部嵌套表格(序号)
  ///datas 数据
  static Widget _contentSerial(
      BuildContext context, List<PurContractListBean> datas) {
    var children = <TableRow>[];
    for (int i = 0; i < datas.length; i++) {
      _index++; //fixme 序号加一
      List<Widget> rowChildren = [];
      //序号
      var TheSerial = _text("$_index");
      rowChildren.add(TheSerial);
      var tableRow = TableRow(
          // decoration: BoxDecoration(color: _getColor(_index + 1)),
          // decoration: BoxDecoration(color: _getColor(i)),
          children: rowChildren);
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.symmetric(
          inside: BorderSide(
              color: _BorderColor, width: _width, style: BorderStyle.solid),
          outside: BorderSide.none),
      children: children,
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///内部嵌套表格(内容)
  ///datas 数据
  static Widget _contentAll(
      BuildContext context,
      List<PurContractListBean> datas,
      PurContractListBean firstData,
      bool isMT01) {
    var children = <TableRow>[];
    for (int i = 0; i < datas.length; i++) {
      var data = datas[i];
      List<Widget> rowChildren = [];
      //请购单号 PurCode
      var PurCode = _text("${data.PurCode}");
      rowChildren.add(PurCode);
      //物料类型
      var MaterialType = _text("${data.getMaterialTypeName(context)}");
      rowChildren.add(MaterialType);
      //物料名称
      var MaterialName = _text("${data.MaterialName}");
      rowChildren.add(MaterialName);
      //物料编码
      var MaterialCode = _text("${data.MaterialCode}");
      rowChildren.add(MaterialCode);
      if (isMT01) {
        //宽
        var ItemWidth = _text(data?.Width);
        rowChildren.add(ItemWidth);
        //高
        var ItemHeight = _text(data?.Height);
        rowChildren.add(ItemHeight);
      }
      //规格型号
      var Width_Height = StatefulBuilder(
        builder: (contxet, setState) {
          var Size = "";
          if (isMT01) {
            Size = "${data?.Width}*${data?.Height}";
          } else {
            Size = data?.Size ?? "";
          }
          return _text(Size);
        },
      );
      rowChildren.add(Width_Height);
      if (!isMT01) {
        //fixme 请购数量 ========================================================================
        var MainNum = StatefulBuilder(
          builder: (contxet, setState) {
            return UiBase.itemWithSigleEdit(
              context,
              data?.POMinNum,
              isAllowEmpty: true,
              isDecimal: true,
              readOnly: true,
              isNegative: false,
            );
          },
        );
        rowChildren.add(MainNum);
      }
      //单位
      var POMainUnit = StatefulBuilder(
        builder: (contxet, setState) {
          return UiBase.itemWithSigleEdit(
            context,
            data?.POMainUnit,
            isAllowEmpty: true,
            isDecimal: true,
            readOnly: true,
            isNegative: false,
          );
        },
      );
      rowChildren.add(POMainUnit);
      //fixme 采购数量 ============================================================================
      var NumberOfApplications3 = StatefulBuilder(
        builder: (contxet, setState) {
          return UiBase.itemWithSigleEdit(context, data?.MainNum,
              isAllowEmpty: true,
              isDecimal: true,
              readOnly: true,
              isNegative: false);
        },
      );
      rowChildren.add(NumberOfApplications3);
      if (isMT01) {
        //面积
        var StockArea = StatefulBuilder(
          builder: (contxet, setState) {
            return _text("${data?.SubsidiaryNum}");
          },
        );
        rowChildren.add(StockArea);
        //areaprice 面积单价
        var areaprice = StatefulBuilder(
          builder: (contxet, setState) {
            var one = _text("${data?.areaprice}");
            if (data.isChange()) {
              var isSame =
                  StringUtils.isSame(data?.areaprice, data?.ChangeAreaPrice);
              if (!isSame) {
                //fixme 不相同
                var two =
                    _text("${data?.ChangeAreaPrice}", isRed: true); //最新的，用红色表示。
                return Column(
                  children: [one, two],
                  mainAxisAlignment: MainAxisAlignment.center,
                );
              }
            }
            return one;
          },
        );
        rowChildren.add(areaprice);
        //顿重
        var tons = StatefulBuilder(
          builder: (contxet, setState) {
            return UiBase.itemWithSigleEdit(context, data?.tons,
                isAllowEmpty: true,
                isDecimal: true,
                readOnly: true,
                isNegative: false);
          },
        );
        rowChildren.add(tons);
        //tonsprice 顿重单价
        var tonsprice = StatefulBuilder(
          builder: (contxet, setState) {
            return UiBase.itemWithSigleEdit(context, data?.tonsprice,
                isAllowEmpty: true,
                isDecimal: true,
                readOnly: true,
                isNegative: false);
          },
        );
        rowChildren.add(tonsprice);
      } else {
        //单价
        var Price = StatefulBuilder(
          builder: (contxet, setState) {
            var one = _text("${data?.Price}");
            if (data.isChange()) {
              var isSame = StringUtils.isSame(data?.Price, data?.ChangePrice);
              if (!isSame) {
                //fixme 不相同
                var two =
                    _text("${data?.ChangePrice}", isRed: true); //最新的，用红色表示。
                return Column(
                  children: [one, two],
                  mainAxisAlignment: MainAxisAlignment.center,
                );
              }
            }
            return one;
          },
        );
        rowChildren.add(Price);
      }
      //金额
      var Amount = StatefulBuilder(
        builder: (contxet, setState) {
          return _text("${data?.Amount}");
        },
      );
      rowChildren.add(Amount);
      if (isMT01) {
        //质量等级
        var QualityGrade = StatefulBuilder(
          builder: (contxet, setState) {
            var one = _text("${data?.QualityGradeName}");
            if (data.isChange()) {
              var isSame = StringUtils.isSame(
                  data?.QualityGrade, data?.ChangeQualityGrade);
              if (!isSame) {
                //fixme 不相同
                var two = _text("${data?.ChangeQualityGradeName}",
                    isRed: true); //最新的，用红色表示。
                return Column(
                  children: [one, two],
                  mainAxisAlignment: MainAxisAlignment.center,
                );
              }
            }
            return one;
          },
        );
        rowChildren.add(QualityGrade);
      }
      //品牌
      var ManufacturerName = StatefulBuilder(
        builder: (contxet, setState) {
          var one = _text("${data?.ManufacturerName}");
          if (data.isChange()) {
            var isSame = StringUtils.isSame(
                data?.ManufacturerId, data?.ChangeManufacturerId);
            if (!isSame) {
              //fixme 不相同
              var two = _text("${data?.ChangeManufacturerName}",
                  isRed: true); //最新的，用红色表示。
              return Column(
                children: [one, two],
                mainAxisAlignment: MainAxisAlignment.center,
              );
            }
          }
          return one;
        },
      );
      rowChildren.add(ManufacturerName);
      //备注
      var ListBeizhu = _text("${data?.ListBeizhu}");
      rowChildren.add(ListBeizhu);
      var tableRow = TableRow(
          // decoration: BoxDecoration(color: _getColor(_index + 1)),
          // decoration: BoxDecoration(color: _getColor(i)),
          children: rowChildren);
      children.add(tableRow);
    }
    var table = Table(
      border: TableBorder.symmetric(
          inside: BorderSide(
              color: _BorderColor, width: _width, style: BorderStyle.solid),
          outside: BorderSide.none),
      children: children,
      columnWidths: _columnWidths(),
      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
    );
    return table;
  }

  ///获取库存数量
  static getStockNum(BuildContext context,
      StateSetter? CurrentInventorySetState, PurDemand data) {
    ///data?.StockNum
    MaterialModel.getStockNum(context, data, false, (value) {
      if (value.isSuccessForCode()) {
        CurrentInventorySetState?.call(() {
          data?.StockNum = value.StockNum;
          //print("物料请购库存：${data?.StockNum}");
        });
      }
    });
  }

  //fixme 条目颜色背景
  static Color _getColor(int i) {
    Color _color = _backgroundColorWithWhite;
    //print("=============$i ${i%2}");
    if (i % 2 == 0) {
      _color = _backgroundColorWithGrey;
    }
    return _color;
  }

  //文本
  static Widget _text(String? text,
      {bool isStart = false, bool isRed = false}) {
    // return Center(
    //   child: Text(text ?? ""),
    // );
    Widget child;
    var textStyle = AppStyle.textStyleWithCard();
    if (isRed) {
      textStyle = AppStyle.textStyleWithCardRed();
    }
    if (isStart) {
      var textKey = Text(
        text ?? "",
        style: textStyle,
      );
      var value = "*";
      var startText = Text(
        value,
        softWrap: true,
        style: AppStyle.textStyleWithCardRed(),
      );
      child = SizedBox(
        child: Row(
          children: [textKey, startText],
          mainAxisAlignment: MainAxisAlignment.center,
        ),
        width: 120,
      );
    } else {
      child = Text(
        text ?? "",
        style: textStyle,
      );
    }
    return Center(
      child: ConstrainedBox(
        constraints: BoxConstraints(
          minHeight: 36.0, //最小高度
        ),
        child: Center(
          child: child,
        ),
      ),
    );
  }

  //复选框
  //isChecked 是否选中
  //isEnable 是否可操作
  //onChanged 选中回调
  static Widget _checkbox(bool isChecked,
      {bool isEnable = true, Function(bool)? onChanged}) {
    Color activeColor = Colors.blueAccent;
    Color inactiveColor = Colors.black;
    if (!isEnable) {
      //不可用，颜色变暗。
      activeColor = Colors.black12;
      inactiveColor = Colors.black12;
    }
    return Container(
      alignment: Alignment.center,
      // height: 30,
      // width: 30,
      padding: EdgeInsets.zero,
      margin: EdgeInsets.zero,
      child: CircleCheckbox(
        isEnable: isEnable,
        value: isChecked,
        //value 是否选中
        width: 20,
        //width 宽度
        height: 20,
        //height 高度
        activeColor: activeColor,
        //activeColor 选中时背景颜色
        inactiveColor: inactiveColor,
        //inactiveColor 未选中时颜色
        style: CircleCheckboxStyle.tick_hollow,
        //circle_point 圆点样式
        //checked: , 自定义选中组件；fixme 优先级比以上属性设置要高。
        //unChecked: ,自定义未选中组件
        onChanged: (bool) {
          //选中状态改变时回调，如点击时。
          //选中状态改变时回调。
          //setState(() {});
          if (isEnable) {
            onChanged?.call(bool);
          }
        },
      ),
    );
  }

  ///按钮
  static Widget _materialButton(String text,
      {VoidCallback? onPressed,
      double radius = 5,
      double height = 35,
      double width = 50,
      Color color = Colors.blueAccent,
      Color textColor = Colors.white,
      double fontSize = 14,
      EdgeInsetsGeometry margin = const EdgeInsets.only(left: 8, right: 8),
      EdgeInsetsGeometry padding =
          const EdgeInsets.only(left: 16, right: 16)}) {
    return Container(
      margin: margin,
      child: MaterialButton(
        padding: padding,
        height: height,
        minWidth: width,
        onPressed: () {
          onPressed?.call();
        },
        //label 右边控件（一般为文本），不能为空
        color: color,
        //color 按钮颜色
        splashColor: Colors.black12,
        //splashColor 点击时，飞溅扩散的颜色
        //highlightColor: Colors.red, //highlightColor 点击时按钮颜色
        colorBrightness: Brightness.light,
        //colorBrightness 按钮亮度；Brightness.dark 暗系风格;Brightness.light 高亮(默认)
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.all(Radius.circular(radius))),
        //shape 形状
        textColor: Colors.white,
        //文本默认颜色
        child: Text(
          text,
          style: TextStyle(
            color: textColor,
            fontSize: fontSize,
          ),
        ), //fixme 子控件
      ),
    );
  }
}
